import { RouteRecordRaw, RouteLocationNormalized } from 'vue-router';
/**
 * 判断当前to路由 是否已经注入到router列表中
 * @param {RouteLocationNormalized} to 跳转路由
 * @param {Array<RouteRecordRaw>} list 路由列表
 * @returns {boolean} 是否已经注入到router列表中
 */
export function hasPermission(to: RouteLocationNormalized, list: Array<RouteRecordRaw>): boolean {
  return list.some(item => item.path == to.path);
}

/**
 * async路由列表是否拥有该路由  用于判断跳转401 404
 * @param {RouteLocationNormalized} to 跳转路由
 * @param {Array<RouteRecordRaw>} list 路由列表
 * @returns {boolean} async路由列表是否拥有该路由
 */
export function hasRouter(to: RouteLocationNormalized, list: Array<RouteRecordRaw>): boolean {
  return list.some(item => {
    let hasPath = to.path == item.path;
    if (!hasPath && item.children?.length) {
      hasPath = hasRouter(to, item.children);
    }
    return hasPath;
  });
}

/**
 * 递归处理路由重定向问题
 * @param {RouteRecordRaw} list 路由列表
 * @returns {Array<RouteRecordRaw>} 处理完成的路由列表
 */
export function setRouteRedirect(list: Array<RouteRecordRaw>): Array<RouteRecordRaw> {
  return list.map(item => {

    const flag = item?.children?.filter(ele => !ele.meta.hidden).length;

    if (flag) {
      return {
        ...item,
        redirect: item.children[0].path,
        children: setRouteRedirect(item.children)
      };
    } else {
      return item;
    }
  });
}
